#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/21 12:56
# file: dept.py
# author: lotus163
from typing import List, Optional

from ...crud import DeptDao
from ...schemas import SysDeptSch, SysDeptTreeSch


class DeptService:

    async def get_dept_tree(self) -> List[SysDeptTreeSch]:
        dept_schs = await DeptDao.get_list_sch()
        # 按照父id和显示num排序
        depts_sch_order = sorted(dept_schs, key=lambda dept: (dept.parentId, dept.orderNum))
        return self.list_to_tree(depts_sch_order)

    def list_to_tree(self, dept_schs: List[SysDeptSch], parent_id=0) -> List[SysDeptTreeSch]:
        """
        递归获取树形结构数据

        :param data_list: 数据列表
        :param parent_id: 父级id
        :return:
        """
        tree = []
        for dept_sch in dept_schs:
            if dept_sch.parentId == parent_id:
                dept_tree = SysDeptTreeSch(id=dept_sch.deptId, label=dept_sch.deptName)
                tree.append(dept_tree)
                dept_tree.children = self.list_to_tree(dept_schs, dept_tree.id)
        return tree

    async def get_all_dept_ids(self)->List[int]:
        """获取所有的部门ID"""
        dept_dbs = await DeptDao.get_list_db()
        return [dept_db.deptId for dept_db in dept_dbs]

    async def get_dept_ids_and_children(self,deptId:int)->List[int]:
        dept_schs = await DeptDao.get_list_sch()
        # 按照父id和id排序
        depts_sch_order = sorted(dept_schs, key=lambda dept: (dept.parentId, dept.deptId))
        dept_ids_list = [deptId]
        for depts_sch in depts_sch_order:
            if depts_sch.parentId in dept_ids_list:
                dept_ids_list.append(depts_sch.deptId)
        return dept_ids_list




